//
//  LVEmotionLabel.m
//  BaiduTravel
//
//  Created by chen jiedan on 13-8-30.
//  Copyright (c) 2013年 Baidu.com. All rights reserved.
//

#import "LVEmotionLabel.h"
#import "NSString+NSString_Ex_.h"
#import "EmoticonUtils.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"

@implementation LVEmotionDataItem

@synthesize dataType = _dataType;
@synthesize content  = _content;
@synthesize lineNumber=_lineNumber;
@synthesize itemHeight=_itemHeight;
@synthesize contentFrame = _contentFrame;

- (void) dealloc
{
    KF_RELEASE_SAFELY(_content);
    [super dealloc];
}

@end

@implementation LVEmotionLabel{
    NSMutableArray *_drawItemsArray;
}



@synthesize emotionContext = _emotionContext;
@synthesize emotionTextColor=_emotionTextColor;
@synthesize emotionTextFont= _emotionTextFont;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        _drawItemsArray = [[NSMutableArray alloc] init];
    }
    return self;
}


- (void) dealloc
{
    KF_RELEASE_SAFELY(_emotionContext);
    KF_RELEASE_SAFELY(_drawItemsArray);
    KF_RELEASE_SAFELY(_emotionTextColor);
    KF_RELEASE_SAFELY(_emotionTextFont);
    [super dealloc];
}


- (void) setEmotionContext:(NSString *)emotionContext
{
    [emotionContext retain];
    [_emotionContext release];
    _emotionContext = emotionContext;
    
    
    //（1）解析出所有的数据类型

    [_drawItemsArray removeAllObjects];
    if (_drawItemsArray == nil) {
        KF_RELEASE_SAFELY(_drawItemsArray);
    }

    _drawItemsArray =  [[LVEmotionLabel parseContent:_emotionContext withWidth:self.frame.size.width withFont:self.emotionTextFont] retain];
}


+ (CGFloat ) labelHeightForEmotionStr:(NSString *)emotionContext withWidth:(CGFloat)width withFont:(UIFont *)emotionFont
{
    
    NSMutableArray *array =  [LVEmotionLabel parseContent:emotionContext withWidth:width withFont:emotionFont];
    CGFloat totalHeight = 0;
    CGFloat lineHeight = 0;
    NSInteger lineNumber = 0;
   LVEmotionDataItem *lastItems = [array lastObject];
    BOOL lastLineContainText = NO;
    BOOL currentLineContainText = NO;

    for (LVEmotionDataItem *item in array) {
        if (lineNumber == item.lineNumber) {
            if (item.dataType == LVEmotionDataItem_Text) {
                currentLineContainText = YES;
            }
            lineHeight = item.contentFrame.origin.y + item.contentFrame.size.height;
            
        }
        
        if (lineNumber != item.lineNumber) {
    
            
            //新的一行开始
            if (lastLineContainText) {
                lineHeight = lineHeight + 5;
            }
            totalHeight = totalHeight + lineHeight;
            
            
            lineNumber = item.lineNumber;
            lastLineContainText = currentLineContainText;
        }
    }
    
    totalHeight =  lastItems.contentFrame.origin.y + lastItems.contentFrame.size.height;
    if(currentLineContainText){
        totalHeight = totalHeight +5;
    }
    return totalHeight;

}

+(NSMutableArray *)parseContent:(NSString *)emotionContext withWidth:(CGFloat)textWidth withFont:(UIFont *)emotionFont
{
    NSMutableArray *parseItemsArray = [[[NSMutableArray alloc] init] autorelease];
    
    NSString *contentString = [NSString stringWithFormat:@"%@",emotionContext];
    
    NSArray *seperatedArray = [contentString componentsSeparatedByString: @"["];
    NSMutableArray *emotionArray = [[[NSMutableArray alloc] init]autorelease];
    for (int i = 0; i < [seperatedArray count]; i++) {
        NSString *items = [seperatedArray objectAtIndex:i];
        
        NSArray *emotionText =  [items componentsSeparatedByString:@"]"];
        NSString *emotionString = [emotionText objectAtIndex:0];
        if ([emotionText count] > 1) {
            if (emotionString != nil && ![emotionString isEqualToString:@""]) {
                //图片的数据格式为 LVEmotionImage: 打头
                [emotionArray addObject:[NSString stringWithFormat:@"LVEmotionImage:[%@]",emotionString]];
            }
            
            emotionString = [emotionText objectAtIndex:1];
            if (emotionString != nil && ![emotionString isEqualToString:@""]) {
                //文本的数据格式为正常
                [emotionArray addObject:emotionString];
            }
        }else{
            if (emotionString != nil && ![emotionString isEqualToString:@""]) {
                //文本的数据格式为正常
                [emotionArray addObject:emotionString];
            }
        }
    }
    
    
    
    
    //（2）计算所有的数据类型位置
    
    CGFloat startPointX = 0;
    CGFloat startPointY = 0;
    
    NSInteger lineNumber = 0;
    CGFloat   lastHeight = 0;
    
    for (NSString *item in emotionArray) {
        NSRange range = [item rangeOfString:@"LVEmotionImage:"];
        if (range.location == NSNotFound) {
            //普通的文本
            for (int i = 0; i < item.length;  i++) {
                NSString *subChar = [[item substringFromIndex:i] substringToIndex:1];
                
                CGSize size = [subChar sizeWithFont:emotionFont constrainedToSize:CGSizeMake(textWidth, 80) lineBreakMode:UILineBreakModeCharacterWrap];
                BOOL swithToNextLine = NO;
                
                if(startPointX + size.width > textWidth){
                    lineNumber ++;
                    swithToNextLine = YES;
                    startPointX = 0;
                    startPointY = startPointY + lastHeight;
                    lastHeight = 0;
                }else{
                    
                    
                }
                CGRect itemFrame = CGRectMake(startPointX, startPointY, size.width, size.height);
                LVEmotionDataItem *dataItem = [[LVEmotionDataItem alloc] init];
                dataItem.contentFrame = itemFrame;
                dataItem.itemHeight   = size.height;
                dataItem.content = subChar;
                dataItem.lineNumber = lineNumber;
                dataItem.dataType = LVEmotionDataItem_Text;
                [parseItemsArray addObject:dataItem];
                [dataItem release];
                
                startPointX = startPointX + size.width;
                
                if (lastHeight < size.height) {
                    lastHeight = size.height;
                }
            }
            
            
        }else{
            NSString *emotion = [item substringFromIndex:(range.location+range.length)];
            NSString *emotionImageName = [EmoticonUtils getEmoticonFileNameByText:emotion];
            UIImage *emotionImg = [UIImage imageNamed:emotionImageName];
            
            BOOL isQuoteType = NO;
            if (emotionImg == nil) {
                emotionImg = [LVEmotionLabel translateQuote:emotion];
                emotionImageName = emotion;
                isQuoteType = YES;
            }
            CGSize imageSize = emotionImg.size;
            
            BOOL swithToNextLine = NO;
            if(startPointX + imageSize.width > textWidth){
                startPointX = 0;
                swithToNextLine = YES;
                lineNumber ++;
                startPointY = startPointY + lastHeight;
                lastHeight  = 0;
            }else{
                
            }
            
            LVEmotionDataItem *dataItem = [[LVEmotionDataItem alloc] init];
            CGRect itemFrame = CGRectZero;
            if (!isQuoteType) {
               itemFrame = CGRectMake(startPointX, startPointY+6, imageSize.width, imageSize.height);
            } else {
               itemFrame = CGRectMake(startPointX, startPointY, imageSize.width, imageSize.height);
            }
            dataItem.dataType = LVEmotionDataItem_EmotionImage;
            dataItem.contentFrame = itemFrame;
            dataItem.itemHeight   = imageSize.height;
            dataItem.content = emotionImageName;
            dataItem.lineNumber = lineNumber;
            [parseItemsArray addObject:dataItem];
            [dataItem release];
            
            startPointX = startPointX + imageSize.width;
            if (lastHeight < imageSize.height) {
                lastHeight = imageSize.height;
            }
        }
    }
    
    
    int totalItem = [parseItemsArray count];
    int startIndex= 0;
    int endIndex  = 0;
    int lastLine = -1;
    CGFloat currentLineHeight = 0;
    
    for (int i  = 0; i < totalItem; i ++) {
        endIndex = i;
        
        LVEmotionDataItem *dataItem = [parseItemsArray objectAtIndex:i];
        
        if (dataItem.lineNumber == lastLine) {
            if (currentLineHeight < dataItem.itemHeight) {
                currentLineHeight = dataItem.itemHeight;
            }
            
            
        }else{
            //新的一行
            lastLine ++;
            
            for (int j = startIndex; j < endIndex; j++) {
                LVEmotionDataItem *lineItems = [parseItemsArray objectAtIndex:j];
                CGRect frame = lineItems.contentFrame;
                frame.origin.y = frame.origin.y + currentLineHeight - frame.size.height;
                lineItems.contentFrame = frame;
            }
            
            
            startIndex = i;
            currentLineHeight = dataItem.itemHeight;
        }
        
        //最后一行
        if (i == totalItem -1) {
            for (int j = startIndex; j <= endIndex; j++) {
                LVEmotionDataItem *lineItems = [parseItemsArray objectAtIndex:j];
                CGRect frame = lineItems.contentFrame;
                frame.origin.y =frame.origin.y + currentLineHeight - frame.size.height;
                lineItems.contentFrame = frame;
            }
        }
        
        
    }
    
    return parseItemsArray;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, self.bounds);
    
    //绘制
    for (LVEmotionDataItem *item in _drawItemsArray) {
        if (item.dataType == LVEmotionDataItem_Text) {
            NSString *textContent = item.content;
            CGRect    itemFrame = item.contentFrame;
            
            //将文本绘制得低一些
            itemFrame.origin.y = itemFrame.origin.y + 5;
            
            [self.emotionTextColor set];
            [textContent drawInRect:itemFrame withFont:self.emotionTextFont lineBreakMode:NSLineBreakByWordWrapping];
            
        }else if (item.dataType == LVEmotionDataItem_EmotionImage){
            UIImage *emotionImg = nil;
            emotionImg = [UIImage imageNamed:item.content];
            if (emotionImg == nil) {
                emotionImg = [LVEmotionLabel translateQuote:item.content];
            }
            CGRect    itemFrame = item.contentFrame;
            [emotionImg drawInRect:itemFrame];
        }
    }
    
    
}

#pragma mark quotes parse method
+ (UIImage *)translateQuote:(NSString*)quoteName
{
    if ([kLeftQuote isEqualToString:quoteName]) {
        return [UIImage imageNamed:@"lv_hotelDetailPage_quotation_left.png"];
    } else if ([kRightQuote isEqualToString:quoteName]) {
        return [UIImage imageNamed:@"lv_hotelDetailPage_quotation_right.png"];
    }else {
        
    }
    
    return nil;
}

@end
